package com.lecyon.farm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lecyon.farm.base.BaseRequestPageVo;
import com.lecyon.farm.base.BaseRequestVo;
import com.lecyon.farm.base.BaseResponse;
import com.lecyon.farm.base.RestResponse;
import com.lecyon.farm.common.CommonService;
import com.lecyon.farm.common.constant.CommonConstant;
import com.lecyon.farm.common.enums.ExcelFileEnum;
import com.lecyon.farm.common.exception.FarmException;
import com.lecyon.farm.entity.ObjectStoresConfig;
import com.lecyon.farm.mapper.ObjectStoresConfigMapper;
import com.lecyon.farm.service.IExcelService;
import com.lecyon.farm.service.IObjectStoresConfigService;
import com.lecyon.farm.util.ResultUtil;
import com.lecyon.farm.util.StringHelper;
import com.lecyon.farm.util.ValidateUtils;
import com.lecyon.farm.vo.add.AddObjectStoresConfigVo;
import com.lecyon.farm.vo.copy.DuplicateVo;
import com.lecyon.farm.vo.export.ExportObjectStoresConfigVo;
import com.lecyon.farm.vo.modify.ModifyObjectStoresConfigVo;
import com.lecyon.farm.vo.query.QueryObjectStoresConfigVo;
import com.lecyon.farm.vo.request.IdsVo;
import com.lecyon.farm.vo.status.StatusVo;
import com.lecyon.farm.vo.view.ObjectStoresConfigVo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * 对象存储配置信息 服务实现类
 *
 * @author YaoZheng
 * @since 2020-04-20
 */
@Service
public class ObjectStoresConfigServiceImpl extends ServiceImpl<ObjectStoresConfigMapper, ObjectStoresConfig> implements IObjectStoresConfigService {

    private static final Logger LOG = LoggerFactory.getLogger(ObjectStoresConfigServiceImpl.class);

    private static final String systemDefaultOperators = "alibaba";

    private ObjectStoresConfigMapper mapper;

    private IExcelService excelService;

    /**
     * 新增同步信息设定
     *
     * @param addVo 新增同步信息设定对象
     * @return 新增记录的id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse<Long> add(AddObjectStoresConfigVo addVo) {
        RestResponse<Long> result = new RestResponse<>();
        //有效性校验
        //必填项校验
        //重复性校验
        boolean flag = isExist(addVo.getOperators(), addVo.getEndPoint());
        if (flag) {
            return ResultUtil.error(result, CommonConstant.EX_FORM_VALIDATE_UNIQUE, "数据重复");
        }
        ObjectStoresConfig entity = new ObjectStoresConfig();
        BeanUtils.copyProperties(addVo, entity);
        //逻辑校验
        result = logicValidate(entity, result);
        if (!result.isSuccess()) {
            return result;
        }
        flag = entity.insert();
        if (!flag) {
            LOG.warn("ObjectStoresConfig add method invoke failed. vo :{}", addVo.toString());
            return ResultUtil.error(null, CommonConstant.EX_DB_INSERT_ERROR, "新增失败！");
        }
        LOG.info("ObjectStoresConfig add method invoke success. vo : {}", addVo.toString());
        return ResultUtil.success(null, entity.getId());
    }

    @Override
    public RestResponse<Long> cumulative(AddObjectStoresConfigVo addVo) {
        return null;
    }

    /**
     * 编辑同步信息设定
     *
     * @param modifyVo 编辑对象
     * @return RestResponse
     */
    @Override
    public RestResponse<Long> modify(ModifyObjectStoresConfigVo modifyVo) {
        //有效性校验
        //必填项校验
        RestResponse<Long> result = new RestResponse<>();
        ObjectStoresConfig entity = new ObjectStoresConfig();
        BeanUtils.copyProperties(modifyVo, entity);
        //逻辑校验
        result = logicValidate(entity, result);
        if (!result.isSuccess()) {
            return result;
        }
        boolean flag = entity.updateById();
        if (!flag) {
            LOG.warn("ObjectStoresConfig modify method invoke failed. vo :{}", modifyVo.toString());
            return ResultUtil.error(null, CommonConstant.EX_DB_UPDATE_ERROR, "编辑失败！");
        }
        LOG.info("ObjectStoresConfig modify method invoke success. vo : {}", modifyVo.toString());
        return ResultUtil.success(null, entity.getId());
    }

    /**
     * 复制同步信息设定
     *
     * @param duplicateVo 复制对象Vo
     * @return
     */
    @Override
    public RestResponse<Long> duplicate(DuplicateVo duplicateVo) {
        return null;
    }

    @Override
    public BaseResponse changeStatus(StatusVo statusVo) {
        return null;
    }

    /**
     * 获取系统默认的对象存储配置信息
     *
     * @return
     */
    @Override
    public ObjectStoresConfigVo getDefault() {
        ObjectStoresConfigVo result = new ObjectStoresConfigVo();
        QueryWrapper<ObjectStoresConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", CommonConstant.DEL_FLAG_UNDELETED).eq("operators", systemDefaultOperators);
        List<ObjectStoresConfig> resultList = list(queryWrapper);
        if (CollectionUtils.isNotEmpty(resultList)) {
            ObjectStoresConfig defaultResult = resultList.get(0);
            BeanUtils.copyProperties(defaultResult, result);
        }
        return result;
    }

    /**
     * 查看记录
     *
     * @param vo 查询条件(id)
     * @return 查询结果
     */
    @Override
    public RestResponse<ObjectStoresConfigVo> get(QueryObjectStoresConfigVo vo) {
        RestResponse<ObjectStoresConfigVo> result = new RestResponse<>();
        if (ValidateUtils.isNullOrEmpty(vo) || ValidateUtils.isNullOrEmpty(vo.getId())) {
            return ResultUtil.error(result, CommonConstant.EX_FORM_VALIDATE_REQUIRED, "缺少必要的查询条件！");
        }
        ObjectStoresConfigVo resultVo = mapper.selectByPrimaryKey(vo);
        if (ValidateUtils.isNullOrEmpty(resultVo)) {
            return ResultUtil.error(result, CommonConstant.EX_DB_SELECT_MISS, "未找到符合条件的记录！");
        }
        return ResultUtil.success(result, resultVo);
    }

    /**
     * 查询列表
     *
     * @param vo 查询条件(包含分页）
     * @return 查询结果
     */
    @Override
    public RestResponse<Page<ObjectStoresConfigVo>> getPageList(BaseRequestPageVo<QueryObjectStoresConfigVo> vo) {
        RestResponse<Page<ObjectStoresConfigVo>> result = new RestResponse<>();
        QueryObjectStoresConfigVo queryCondition = vo.getEntity(QueryObjectStoresConfigVo.class);
        Page<ObjectStoresConfigVo> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        if (CollectionUtils.isNotEmpty(vo.getOrders())) {
            List<OrderItem> orderItemList = CommonService.batchAddPrefix4OrderColumn(vo.getOrders());
            page.setOrders(orderItemList);
        } else {
            page.setOrders(CommonConstant.orderItemList);
        }
        page = mapper.selectByPage(page, queryCondition);
        return ResultUtil.success(result, page);
    }

    /**
     * 查询列表
     *
     * @param vo 查询条件（不含分页信息）
     * @return 查询结果
     */
    @Override
    public RestResponse<List<ObjectStoresConfigVo>> getList(BaseRequestVo<QueryObjectStoresConfigVo> vo) {
        RestResponse<List<ObjectStoresConfigVo>> result = new RestResponse<>();
        QueryObjectStoresConfigVo queryCondition = vo.getEntity(QueryObjectStoresConfigVo.class);
        List<ObjectStoresConfigVo> resultVoList = mapper.selectByCondition(queryCondition);
        return ResultUtil.success(result, resultVoList);
    }

    /**
     * 根据条件查询结果,并导出到Excel
     *
     * @param vo 查询条件
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse<String> exportExcel(BaseRequestVo<QueryObjectStoresConfigVo> vo) {
        RestResponse<String> result = new RestResponse<>();
        List<ExportObjectStoresConfigVo> resultList = Lists.newArrayList();
        RestResponse<List<ObjectStoresConfigVo>> queryResult = getList(vo);
        List<ObjectStoresConfigVo> voList = null;
        if (queryResult.isSuccess()) {
            voList = queryResult.getData();
        }
        if (CollectionUtils.isNotEmpty(voList)) {
            for (ObjectStoresConfigVo temp : voList) {
                ExportObjectStoresConfigVo exportVo = new ExportObjectStoresConfigVo();
                BeanUtils.copyProperties(temp, exportVo);
                resultList.add(exportVo);
            }
        }
        String downLoadUrl;
        try {
            downLoadUrl = excelService.exportExcel(resultList, ExcelFileEnum.FM_WORK);
            if (StringHelper.isEmpty(downLoadUrl)) {
                return ResultUtil.success(result, downLoadUrl);
            }
        } catch (IOException e) {
            throw new FarmException(CommonConstant.EX_EXCEL_ERROR, e.getMessage());
        }
        return ResultUtil.success(result, downLoadUrl);
    }

    /**
     * 通用删除方法，包含批量删除与单条删除
     *
     * @param vo 删除条件
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse delete(@NotNull IdsVo vo) {
        if (ValidateUtils.isNullOrEmpty(vo.getId()) && CollectionUtils.isEmpty(vo.getIdsList())) {
            LOG.warn("ObjectStoresConfig delete params is null.", this.getClass().getSimpleName());
            return ResultUtil.error(CommonConstant.EX_FORM_VALIDATE_REQUIRED, "缺少必要的参数！");
        }
        List<Long> idsList = vo.getIdsList();
        if (CollectionUtils.isNotEmpty(idsList)) {
            //如果idList不为空，优先进行批量删除
            return deleteByIds(idsList);
        }
        Long id = vo.getId();
        return deleteById(id);
    }

    /**
     * 删除同步信息设定
     *
     * @param id 主键ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse deleteById(Long id) {
        boolean flag = removeById(id);
        if (!flag) {
            LOG.error("ObjectStoresConfig delete unsuccessful. id :{}", id);
            return ResultUtil.error(CommonConstant.EX_DB_DELETE_ERROR, "删除记录失败！");
        }
        return ResultUtil.success();
    }

    /**
     * 批量删除同步信息设定
     *
     * @param idList 主键ID列表
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse deleteByIds(List<Long> idList) {
        boolean flag = removeByIds(idList);
        if (!flag) {
            LOG.error("ObjectStoresConfig delete batch unsuccessful. ids :{}", idList);
            return ResultUtil.error(CommonConstant.EX_DB_DELETE_ERROR, "批量删除失败");
        }
        return ResultUtil.success();
    }

    /**
     * 逻辑校验规则
     *
     * @param entity       被校验的实体类
     * @param restResponse 消息传递对象
     * @return 结果
     */
    private RestResponse logicValidate(ObjectStoresConfig entity, RestResponse restResponse) {
        return ResultUtil.success(restResponse, null);
    }

    /**
     * 查询记录是否重复
     * 标准：作业编号
     *
     * @param operators 唯一性条件
     * @param endPoint  节点
     * @return
     */
    private boolean isExist(String operators, String endPoint) {
        if (StringHelper.isEmpty(operators) || StringHelper.isEmpty(endPoint)) {
            return false;
        }
        int count = mapper.selectCount(new QueryWrapper<ObjectStoresConfig>()
                .eq("operators", operators)
                .eq("end_point", endPoint)
                .eq("del_flag", CommonConstant.DEL_FLAG_UNDELETED));
        return count > 0 ? true : false;
    }

    /**
     * ----------------------------- 分割线 以下是setter方法，用于替换field上的@Autowired -----------------------------
     **/

    @Autowired
    public void setMapper(ObjectStoresConfigMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    @Lazy
    public void setExcelService(IExcelService excelService) {
        this.excelService = excelService;
    }

}
